package top.wilsonlv.jaguar.webrtc.demo;

import dev.onvoid.webrtc.*;
import dev.onvoid.webrtc.media.video.VideoDeviceSource;
import dev.onvoid.webrtc.media.video.VideoTrack;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lvws
 * @since 2025/1/9
 */
@Slf4j
public class Offer {

    private final PeerConnectionFactory factory = new PeerConnectionFactory();

    @Getter
    @Setter
    private RTCPeerConnection remotePeerConnection = null;

    private final PeerConnectionObserver observer = new PeerConnectionObserver() {
        @Override
        public void onIceCandidate(RTCIceCandidate rtcIceCandidate) {
            log.info("onIceCandidate");
            remotePeerConnection.addIceCandidate(rtcIceCandidate);
        }

        @Override
        public void onIceConnectionChange(RTCIceConnectionState state) {
            log.info(state.toString());
        }
    };

    @Getter
    private final RTCPeerConnection peerConnection = factory.createPeerConnection(new RTCConfiguration(), observer);


    public void init() {
        VideoDeviceSource videoSource = new VideoDeviceSource();
        videoSource.start();

        VideoTrack video = factory.createVideoTrack("videoTrack", videoSource);

        List<String> streamIds = new ArrayList<>();
        streamIds.add("stream-0");

        peerConnection.addTrack(video, streamIds);
        log.info("inited");
    }

    public void crateOffer(Answer answer) {
        peerConnection.createOffer(new RTCOfferOptions(), new CreateSessionDescriptionObserver() {
            @Override
            public void onSuccess(RTCSessionDescription description) {
                log.info("createOffer success");

                peerConnection.setLocalDescription(description, new SetSessionDescriptionObserver() {
                    @Override
                    public void onSuccess() {
                        log.info("setLocalDescription  success");
                    }

                    @Override
                    public void onFailure(String error) {
                        log.error(error);
                    }
                });

                new Thread(() -> answer.crateAnswer(peerConnection, description)).start();
            }

            @Override
            public void onFailure(String error) {
                log.error(error);
            }
        });
    }

}
